package middleware

import (
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"net/http"
	"runtime/debug"
	"wzgames/pkg/logger"
	"wzgames/pkg/server/http/types"
)

func Recovery() gin.HandlerFunc {
	return func(c *gin.Context) {
		defer func() {
			if err := recover(); err != nil {
				traceId := c.Writer.Header().Get("X-Request-Trace-Id")
				c.Abort()
				response := types.Response{
					Code:    500,
					Message: "server internal error",
				}
				logger.Error("server internal error", zap.String("trace_id", traceId),
					zap.String("uri", c.Request.URL.Path), zap.String("remote_addr", c.ClientIP()),
					zap.String("stack", string(debug.Stack())))

				c.JSON(http.StatusUnauthorized, response)
				return
			}
		}()

		c.Next()
	}
}
